<template>
  <div class="container">
    <div class="content-wrapper">
      <div class="search-section">
        <el-form :model="queryForm" class="search-form">
          <div class="basic-search-row">
            <el-form-item style="margin-bottom: 0px" label="角色名称">
              <el-input
                v-model.trim="queryForm.roleName"
                placeholder="请输入角色名称"
                clearable
                prefix-icon="Search"
                @keyup.enter="getRoleList"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <div class="search-actions">
              <el-button type="primary" icon="Search" @click="getRoleList">搜索</el-button>
              <el-button icon="RefreshRight" @click="resetQuery">重置</el-button>
              <el-button @click="toggleAdvancedSearch" :icon="isAdvancedSearchVisible ? 'ArrowUp' : 'ArrowDown'">
                {{ isAdvancedSearchVisible ? '收起' : '展开' }}
              </el-button>
            </div>
          </div>

          <div v-if="isAdvancedSearchVisible" class="advanced-search-row">
            <el-form-item style="margin-bottom: 0px" label="角色标识">
              <el-input
                v-model.trim="queryForm.roleKey"
                placeholder="请输入角色标识"
                clearable
                prefix-icon="Document"
                @keyup.enter="getRoleList"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom: 0px" label="状态">
              <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 200px">
                <el-option label="正常" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item>
          </div>
        </el-form>

        <div class="operation-container">
          <el-button type="primary" icon="Plus" @click="addRole">新增角色</el-button>
          <el-tooltip content="刷新数据" placement="top" effect="light">
            <el-button icon="RefreshRight" circle @click="getRoleList"></el-button>
          </el-tooltip>
        </div>
      </div>

      <div class="table-section">
        <el-table v-loading="loading" :data="roleList" border stripe highlight-current-row class="role-table">
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column prop="roleKey" label="角色标识" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="roleName" label="角色名称" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="remark" label="备注" align="center" />
          <el-table-column prop="status" label="状态" align="center" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :disabled="row.username === 'admin'"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleStatusChange(row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              <el-tooltip :content="row.createTime" placement="top" effect="light">
                <span class="time-cell">
                  <el-icon><Calendar /></el-icon>
                  {{ row.createTime }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="{ row }">
              <el-tooltip content="授权菜单" placement="top" effect="light">
                <el-button type="primary" link icon="Setting" @click="handleAuthMenu(row)"></el-button>
              </el-tooltip>
              <el-tooltip content="修改角色" placement="top" effect="light">
                <el-button type="primary" link icon="Edit" @click="handleEdit(row)"></el-button>
              </el-tooltip>
              <el-popconfirm
                title="你确定删除这条数据？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="Warning"
                icon-color="#ff4949"
                :title-style="{ color: '#1e293b', fontSize: '14px', fontWeight: 500 }"
                @confirm="handleDeleteRole(row)"
              >
                <template #reference>
                  <el-button type="danger" link icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="onSizeChange"
          @current-change="onPageChange"
          background
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <edit-role ref="editRoleRef" @refresh="getRoleList"></edit-role>

    <auth-menu ref="authMenuRef"></auth-menu>
  </div>
</template>

<script setup>
  import { useRoleApi } from '@/api/role-api.js';
  import { DialogType, RStatus } from '@/common/comstants.js';
  import editRole from './components/EditRole.vue';
  import authMenu from './components/AuthMenu.vue';

  let roleList = reactive([]);
  let total = ref(0);
  let loading = ref(false);

  // 控制高级搜索的显示
  const isAdvancedSearchVisible = ref(false);

  // 查询form
  const queryForm = reactive({
    roleKey: '',
    roleName: '',
    status: '',
    page: 1,
    size: 10,
  });
  const editRoleRef = ref();
  const authMenuRef = ref();

  // 使用 reactive 初始化 pagination
  const pagination = reactive({
    page: 1,
    size: 10,
  });

  onMounted(() => {
    getRoleList();
  });

  const onSizeChange = (size) => {
    pagination.size = size;
    getRoleList();
  };

  const onPageChange = (page) => {
    pagination.page = page;
    getRoleList();
  };

  const getRoleList = async () => {
    loading.value = true;
    try {
      const params = {
        page: pagination.page,
        size: pagination.size,
        ...queryForm,
      };
      const res = await useRoleApi().getRoleList(params);

      if (res.status === RStatus.SUCCESS) {
        roleList = res.data.roles || [];
        total.value = res.data.total || 0;
      }
    } catch (error) {
      ElMessage.error('获取角色列表失败: ' + error.message);
    } finally {
      loading.value = false;
    }
  };

  const addRole = () => {
    editRoleRef.value.openDialog();
  };

  const handleEdit = (row) => {
    editRoleRef.value.openDialog(DialogType.EDIT, row);
  };

  const handleStatusChange = async (row) => {
    loading.value = true;
    try {
      const res = await useRoleApi().updateRole(row);
      if (res.status === RStatus.SUCCESS) {
        await getRoleList();
        ElMessage.success(res.message);
      }
    } finally {
      loading.value = false;
    }
  };

  const handleDeleteRole = async (row) => {
    loading.value = true;
    try {
      const res = await useRoleApi().deleteRole(row.roleId);
      if (res.status === RStatus.SUCCESS) {
        await getRoleList();
        ElMessage.success(res.message);
      } else {
        ElMessage.error(res.message);
      }
    } finally {
      loading.value = false;
    }
  };

  const handleAuthMenu = (row) => {
    authMenuRef.value.openDialog(row);
  };

  // 切换高级搜索显示
  const toggleAdvancedSearch = () => {
    isAdvancedSearchVisible.value = !isAdvancedSearchVisible.value;
  };

  // 重置搜索
  const resetQuery = () => {
    queryForm.roleKey = '';
    queryForm.roleName = '';
    queryForm.status = '';
    isAdvancedSearchVisible.value = false;
    getRoleList();
  };
</script>

<style lang="scss" scoped>
  .container {
    background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);

    .content-wrapper {
      background-color: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 20px;
    }

    .search-section {
      display: flex;
      flex-direction: column;
      gap: 15px;

      .search-form {
        display: flex;
        flex-direction: column;
        background-color: rgba(249, 250, 251, 0.6);
        backdrop-filter: blur(8px) saturate(150%);
        border: 1px solid rgba(229, 231, 235, 0.3);
        padding: 15px;
        border-radius: 12px;
        transition: all 0.3s ease;

        .basic-search-row {
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          gap: 15px;
          margin-bottom: 0;
        }

        .advanced-search-row {
          margin-top: 15px;
          display: flex;
          flex-wrap: wrap;
          gap: 15px;
        }

        .search-actions {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }
    }

    .operation-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      gap: 10px;
      flex-wrap: wrap;
    }

    .table-section {
      margin-bottom: 20px;

      .role-table {
        border-radius: 6px;
        overflow: hidden;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 15px;
    }
  }
</style>
@/api/role-api.js